import { reactive, Ref, ref } from "vue";
import { getListApi } from "@/api/configCenter/templateLibrary/index";

export default function InitHook(state: { passData: Ref<TemplateLibrary.ListRows>; type: Ref<number> }) {
  const { passData, type: typeInit } = state;
  //表单数据
  const formState = reactive<Partial<TemplateLibrary.AddForm>>({
    name: undefined,
    description: undefined,
    type: undefined,
    typeCode: undefined,
    fieldList: [],
    nameList: [],
    exportName: undefined
  });

  const dataList = ref<Array<TemplateLibrary.dataList>>([]);

  //表格数据
  const tableData = reactive([]);

  //等待状态
  const loading = ref<boolean>(false);

  //重置数据
  const resetDataList = () => {
    dataList.value.map((t: any) => {
      t.valueData = [];
      t.checkValue = [];
    });
  };

  const init = () => {
    const { name, description, typeCode, fields, type, exportName } = passData.value;
    if (typeInit.value === 2) {
      //编辑
      Object.assign(formState, { name, description, type, typeCode, exportName });
      const filedValue = fields.split(",");
      dataList.value.map((t: any) => {
        t.feilds.map((q: any) => {
          if (filedValue.includes(q.code)) {
            t.checkValue.push(q.code);
          }
        });
      });
    }
  };

  //获取导出内容
  const getExportContentApi = () => {
    loading.value = true;
    getListApi()
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          dataList.value = data.map((t: any) => {
            return { ...t, checkValue: [] };
          });
          init();
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };

  //表单ref
  const formRef = ref(null);
  return {
    tableData,
    formState,
    loading,
    formRef,
    getExportContentApi,
    dataList,
    resetDataList
  };
}
